package com.atguigu.web;

import com.atguigu.pojo.*;
import com.atguigu.service.*;
import com.atguigu.service.impl.*;
import com.atguigu.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

public class ClientServlet extends BaseServlet {
    SubtaskService subtaskService=new SubtaskServiceImpl();
    ServiceService serviceService=new ServiceServiceImpl();
    ServerService serverService=new ServerServiceImpl();
    UpdatePhpCodeTaskService updatePhpCodeTaskService=new UpdatePhpCodeTaskServiceImpl();
    NginxServiceConfigPhpService nginxServiceConfigPhpService=new NginxServiceConfigPhpServiceImpl();
    Gson gson=new Gson();
    ProjectService projectService=new ProjectServiceImpl();
    ProjectModuleService projectModuleService=new ProjectModuleServiceImpl();
    ProjectModuleTypeService projectModuleTypeService=new ProjectModuleTypeServiceImpl();
    TomcatServiceConfigService tomcatServiceConfigService=new TomcatServiceConfigServiceImpl();
    TomcatAndHeartbeatServiceConfigService tomcatAndHeartbeatServiceConfigService=new TomcatAndHeartbeatServiceConfigServiceImpl();
    UpdateTomcatCodeTaskService updateTomcatCodeTaskService=new UpdateTomcatCodeTaskServiceImpl();
    UpdateTomcatCodeAndHeartbeatTaskService updateTomcatCodeAndHeartbeatTaskService=new UpdateTomcatCodeAndHeartbeatTaskServiceImpl();
    BasicBehaviorService basicBehaviorService=new BasicBehaviorServiceImpl();
    MainTaskService mainTaskService=new MainTaskServiceImpl();
    DeployServiceModuleService deployServiceModuleService=new DeployServiceModuleServiceImpl();
    DeployGoalService deployGoalService=new DeployGoalServiceImpl();
    UserService userService=new UserServiceImpl();
    NginxServiceConfigProxyService nginxServiceConfigProxyService=new NginxServiceConfigProxyServiceImpl();


    protected void getSubtaskIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String serverId=request.getParameter("serverId");
        Server server=serverService.queryServerById(serverId);
        if(server==null){
            response.getWriter().write("serverid : "+serverId+" not found");
            return;
        }//排除serverId 无效的情况
        List<Subtask> subtasks=subtaskService.queryNeedDoSubtasksByServerId(serverId);
        //System.out.println(serverId);
        String subtaskIds="";
        for(Subtask subtask:subtasks){
            if(subtaskIds==""){
                subtaskIds=subtask.getId();
            }else {
                subtaskIds=subtaskIds+","+subtask.getId();
            }
            subtask.setStatus("wait");
            subtaskService.updateSubtask(subtask);
        }
        System.out.println(subtaskIds);
        response.getWriter().write(subtaskIds);
        return;
        //response.getWriter().write("hello");
    }
    protected void getSubtaskCommand(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String subtaskId=request.getParameter("subtaskId");
        if(subtaskId==""){
            response.getWriter().write("subtaskId不能为空");
        }
        Subtask subtask=subtaskService.querySubtaskById(subtaskId);
        if(subtask==null){
            response.getWriter().write("subtaskId无效:"+subtaskId);
            return;
        }
        //System.out.println(subtask);
        response.getWriter().write(subtask.getCommand());
    }
    protected void reportSubtaskStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String subtaskId=request.getParameter("subtaskId");
        if(subtaskId==""){
            response.getWriter().write("subtaskId不能为空");
        }
        Subtask subtask=subtaskService.querySubtaskById(subtaskId);
        //System.out.println(taskId);
        if(subtask==null){
            response.getWriter().write("subtaskId无效:"+subtaskId);
            return;
        }

        String status=request.getParameter("status");
        //System.out.println("状态是:"+status);
        subtask.setStatus(status);

        String result=request.getParameter("result");
        //System.out.println("结果是:"+result);
        subtask.setResult(result);
        //System.out.println(subtask);
        subtaskService.updateSubtask(subtask);

        Integer count=subtaskService.querySubtasksByStatusNotTrue();
        if(subtask.getMainTaskType().contains("updatePhpCodeTask")){
            UpdatePhpCodeTask updatePhpCodeTask=updatePhpCodeTaskService.queryUpdatePhpCodeTaskById(subtask.getMainTaskId());
            System.out.printf("本次查看主任务剩余子任务量:"+count);
            if(count==0){
                updatePhpCodeTask.setStatus("complete");
                updatePhpCodeTaskService.updateUpdatePhpCodeTask(updatePhpCodeTask);
            }
        }

        response.getWriter().write("结果已收到");
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    protected void existBasicBehavior(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String clientId=request.getParameter("clientId");
        BasicBehavior basicBehavior=basicBehaviorService.queryBasicBehaviorByStatusMakeAndClientId(clientId);
        if(basicBehavior==null){
            response.getWriter().write("no");
        }else {
            response.getWriter().write("yes");
        }
    }
    protected void getStatusMakeBasicBehavior(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String clientId=request.getParameter("clientId");
        String mainTaskId=request.getParameter("mainTaskId");

        if (mainTaskId.equals("")){//第一次来请求"基础行为"
            BasicBehavior basicBehavior=basicBehaviorService.queryBasicBehaviorByStatusMakeAndClientId(clientId);
            basicBehavior.setStatus("doing");basicBehaviorService.updateBasicBehavior(basicBehavior);
            response.getWriter().write(gson.toJson(basicBehavior));
        }else {//有主任务号:第二次或第2+次
            MainTask mainTask=mainTaskService.queryMainTaskById(mainTaskId);
            if(mainTask.getStatus().equals("make")) {
                System.out.println("主任务id:"+mainTaskId+"状态为make++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
                BasicBehavior basicBehavior = basicBehaviorService.queryBasicBehaviorByStatusMakeAndClientIdAndMainTaskId(clientId, mainTaskId);//第二次来请求"基础行为"
                System.out.println("实际具体任务为:"+basicBehavior.getId()+"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
                System.out.println(basicBehavior);
                basicBehavior.setStatus("doing");basicBehaviorService.updateBasicBehavior(basicBehavior);
                response.getWriter().write(gson.toJson(basicBehavior));
            }else {//主任务除了make就是ok,再要不就是error
                if (mainTask.getStatus().equals("ok")){//那这就是第2个nginx offline/online 后
                    System.out.println("你提交的主任务id状态为ok:"+mainTaskId+",也就是说:虽然你知道有你的任务,但是你提交的主任务id是错误的;所以我需要给你分配一个主任务的下一个主任务的子任务");
                    //response.getWriter().write("");
                    MainTask nextMainTask=mainTaskService.queryMainTaskByLastId(mainTask.getId());
                    BasicBehavior basicBehavior=new BasicBehavior();
                    if(nextMainTask==null){
                        System.out.println("下一个的主任务为空+++++++++++也就是本发布模块完成了++++++++++++++回复client,休息一下吧++++++++++++++++++++++++++++++++");
                        response.getWriter().write("你所请求的主任务已经做完了,而且没有后续任务可做了,休息一下吧");return;
//                        System.out.println("下一个的主任务为空+++++++++++也就是本发布模块完成了++++++++++++++也就是能开始下一个模块的发布了++++++++++++++++++++++++++++++++");
//                        DeployServiceModule newDeployServiceModule=deployServiceModuleService.queryDeployServiceModuleByLastId(mainTask.getDeployServiceModuleId());
//                        //应该比较的是lastMainTask 最后一个basicBehavior的clientId与nextDeployModule的basicBehavior的clientId是否一样
//
//                        BasicBehavior lastBasicBehavior=basicBehaviorService.queryLastBasicBehaviorByMainTaskId(mainTaskId);
//                        BasicBehavior nextBasicBehavior=basicBehaviorService.queryMakeStatusBasicBehaviorByDeployServiceModuleIdAndDeployGoalId(newDeployServiceModule.getId(),newDeployServiceModule.getDeployGoalId());
//                        //System.out.println("最后一个子任务是:"+lastBasicBehavior);
//                        //System.out.println("下一个模块的第一个子任务是:"+nextBasicBehavior);
//                        String lastServerId=lastBasicBehavior.getClientId();
//                        String nextServerId=nextBasicBehavior.getClientId();
//
//                        if (lastServerId.equals(nextServerId)){
//                            basicBehavior = basicBehaviorService.queryBasicBehaviorByStatusMakeAndClientIdAndDeployServiceModuleId(clientId, newDeployServiceModule.getId());
//                        }else{
//                            response.getWriter().write("上一个模块跟下一个模块不在同一个server上");return;
//                        }
                    }else {
                        basicBehavior = basicBehaviorService.queryBasicBehaviorByStatusMakeAndClientIdAndMainTaskId(clientId, nextMainTask.getId());//这个"mainTask",搜索下一个"mainTask"的"基础行为"
                        basicBehavior.setStatus("doing");
                        basicBehaviorService.updateBasicBehavior(basicBehavior);
                        response.getWriter().write(gson.toJson(basicBehavior));
                    }
                }
            }
        }
    }
    protected void reportBasicBehavior(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id=request.getParameter("id");
        String status=request.getParameter("status");
        String result=request.getParameter("result");
        System.out.println("++++++++++========================================"+result.replace("\r|\n",""));

        BasicBehavior basicBehavior=basicBehaviorService.queryBasicBehaviorById(id);
        DeployServiceModule deployServiceModule=deployServiceModuleService.queryDeployServiceModuleById(basicBehavior.getDeployServiceModuleId());
        DeployGoal deployGoal=deployGoalService.queryDeployGoalById(deployServiceModule.getDeployGoalId());
        ProjectModule projectModule=projectModuleService.queryProjectModuleById(deployServiceModule.getProjectModuleId());
        ProjectModuleType projectModuleType=projectModuleTypeService.queryProjectModuleTypeById(projectModule.getProjectModuleTypeId());
        if(basicBehavior==null){
            response.getWriter().write("没有这个id:"+id);return;
        }else {
            MainTask mainTask=mainTaskService.queryMainTaskById(basicBehavior.getMainTaskId());
            if(status.equals("0")){
                basicBehavior.setStatus("ok");
                basicBehavior.setResult(result);
                basicBehaviorService.updateBasicBehavior(basicBehavior);
                //这一条已经执行完了,要看看主任务上是否还有操作
                String mainTaskName=mainTask.getName();
                String yesOrNo="";
                if(mainTaskName.equals("offline")){
                    yesOrNo=offline(basicBehavior);
                    //grep sed reload
                    switch (yesOrNo) {
                        case "yes": //主任务下还有子任务
                            response.getWriter().write("yes");return;
                        case "no"://修改主任务,查询发布类型,获得下一步主任务和子任务 //主任务执行完了
                            if (mainTask.getStatus().equals("ok")){
                                response.getWriter().write("no");return;
                            }else {
                                mainTask.setStatus("ok");mainTaskService.updateMainTask(mainTask);
                                if (projectModuleType.getName().equals("tomcatAndHeartbeat")) {//如果它的类型是tomcat+心跳,就执行tomcat+心跳的类型主任务制定环节
                                    yesOrNo = tomcatAndHeartbeat(mainTask);
                                    if (yesOrNo.equals("yes")) {//返回为yes,tomcat+心跳 这种发布类型,还有其他主任务要执行,且已制定好了.
                                        response.getWriter().write("yes");return;
                                    } else if (yesOrNo.equals("no")) {
                                        response.getWriter().write("no");return;
                                    }
                                }
                            }
                            break;
                        case "error":
                            break;
                    }
                }
                if(mainTaskName.equals("update")){
                    //主任务是update
                    yesOrNo=update(basicBehavior);//查看是否有其他子任务
                    if(yesOrNo.equals("yes")){
                        response.getWriter().write("yes");return;//这里他不会是yes的.
                    }else if(yesOrNo.equals("no")){                        //本主环节完事了,修改本主任务,访问本发布类型,查询是否有下一步的主任务
                        mainTask.setStatus("ok");mainTaskService.updateMainTask(mainTask);
                        if (projectModuleType.getName().equals("tomcatAndHeartbeat")){
                            yesOrNo=tomcatAndHeartbeat(mainTask);//查看是否有其他主任务
                            switch (yesOrNo) {
                                case "yes": //返回为yes,tomcat+心跳 这种发布类型,还有其他主任务要执行,且已制定好了.
                                    response.getWriter().write("yes");return;
                                case "no":
                                    yesOrNo=oneDeployServiceModuleOver(mainTask,deployServiceModule,deployGoal);
                                    response.getWriter().write(yesOrNo);
                                    break;
                                case "error":
                                    break;
                            }
                        }
                    }else if(yesOrNo.equals("error")){//一旦失败,就逐级向上报告error
                        basicBehaviorError(basicBehavior);
                        response.getWriter().write("error");return;
                    }
                }
                if(mainTaskName.equals("online")){
                    yesOrNo=online(basicBehavior);//查看是否有其他子任务
                    switch (yesOrNo) {
                        case "yes":
                            response.getWriter().write("yes");return;
                        case "no": //本模块上线完成,修改主任务状态,修改发布模块状态,查看goal是否有其他任务安排,从而继续
                            if(mainTask.getStatus().equals("ok")){
                                response.getWriter().write("no");return;
                            }else {
                                yesOrNo=oneDeployServiceModuleOver(mainTask,deployServiceModule,deployGoal);
                                response.getWriter().write(yesOrNo);
                            }
                            break;
                        case "error":
                            break;
                    }
                }
                //从这里以上,都是返回状态为0的情况
            }else{
                basicBehavior.setResult(result);
                basicBehaviorError(basicBehavior);
                response.getWriter().write("error");return;
            }
        }
    }

    public String tomcatAndHeartbeat(MainTask lastMainTask){
        String yesOrNo="";

        if(lastMainTask.getName().equals("online")){
            //上一个"主任务是 online ",且运行到这里,说明"结果为ok",那么我决定"从此以后就停止""这种服务形式(tomcatAndHeartbeat)"的更新;换句话说:"就是online,就是最后,一条,我这里就是告诉程序可以终结这种服务的发布活动的操作"
            yesOrNo="no";
        }else{
            //环节 公共部分
            MainTask mainTask=new MainTask();
            mainTask.setId(WebUtils.id());
            mainTask.setDeployServiceModuleId(lastMainTask.getDeployServiceModuleId());
            mainTask.setDeployGoalId(lastMainTask.getDeployGoalId());
            mainTask.setLastId(lastMainTask.getId());
            mainTask.setStatus("make");

            BasicBehavior basicBehavior=new BasicBehavior();
            basicBehavior.setId(WebUtils.id());
            basicBehavior.setMainTaskId(mainTask.getId());
            basicBehavior.setDeployServiceModuleId(mainTask.getDeployServiceModuleId());
            basicBehavior.setDeployGoalId(mainTask.getDeployGoalId());
            basicBehavior.setResult("");
            basicBehavior.setStatus("make");

            String deployServiceModuleId=mainTask.getDeployServiceModuleId();
            DeployServiceModule deployServiceModule=deployServiceModuleService.queryDeployServiceModuleById(deployServiceModuleId);
            TomcatAndHeartbeatServiceConfig tomcatAndHeartbeatServiceConfig=tomcatAndHeartbeatServiceConfigService.queryTomcatAndHeartbeatServiceConfigById(deployServiceModule.getTargetNodeId());
            NginxServiceConfigProxy nginxServiceConfigProxy=nginxServiceConfigProxyService.queryNginxServiceConfigProxyByTargetNodeId(deployServiceModule.getTargetNodeId());

            String tomcatServerId=tomcatAndHeartbeatServiceConfig.getServerId();

            Server targetNodeServer=serverService.queryServerById(tomcatServerId);
            String targetNodeServerIp=targetNodeServer.getIp();
            String httpPort=tomcatAndHeartbeatServiceConfig.getHttpPort();
            //环节 公共部分
            if(lastMainTask.getName().equals("offline")){//在tomcatAndHeartBeat类型发布流程中,offline下一步就是pull,然后就是online
                String nginxServerId=nginxServiceConfigProxy.getServerId();
                mainTask.setName("update");
                basicBehavior.setType("update:pull");//定义这个主任务的第一个子任务

                ProjectModule projectModule=projectModuleService.queryProjectModuleById(deployServiceModule.getProjectModuleId());

                basicBehavior.setClientId(tomcatServerId);

                String deployPullRootUrl=projectModule.getDeployPullRootUrl();
                String sourceWarUrl=WebUtils.addSeparatorChar(deployPullRootUrl)+deployServiceModule.getFileUrl();
                String tomcatHome=WebUtils.addSeparatorChar(tomcatAndHeartbeatServiceConfig.getTomcatHome());
                String targetWarPath=tomcatHome+"webapps/"+deployServiceModule.getFileUrl();
                basicBehavior.setCommand("wget "+sourceWarUrl+" -O "+targetWarPath+";") ;

                //System.out.println("nginxServerId: "+nginxServerId+";tomcatServerId: "+tomcatServerId);
                if(nginxServerId.equals(tomcatServerId)){
                    yesOrNo="yes";
                }else {
                    yesOrNo="no";
                }
                basicBehaviorService.addBasicBehavior(basicBehavior);
                mainTaskService.addMainTask(mainTask);
            }
            if(lastMainTask.getName().equals("update")){//上一个主任务是update,下一个主任务是online
                List<NginxServiceConfigProxy> nginxServiceConfigProxies=nginxServiceConfigProxyService.queryNginxServiceConfigProxysByTargetNodeId(deployServiceModule.getTargetNodeId());
                if(nginxServiceConfigProxies.size()==0){
                    yesOrNo="no";
                }else {
                    String nginxServerId=nginxServiceConfigProxy.getServerId();
                    mainTask.setName("online");
                    basicBehavior.setType("online:grep");
                    basicBehavior.setClientId(nginxServerId);

                    String domain=nginxServiceConfigProxy.getFrontDomain();
                    String nginxVhostConfigFile="/lhwl/app/nginx/conf/vhost/"+domain+".conf";
                    String command="grep -n "+targetNodeServerIp+":"+httpPort+" "+nginxVhostConfigFile;

                    basicBehavior.setCommand(command);

                    if (nginxServiceConfigProxies.size()>1){
                        int i=0;
                        for (NginxServiceConfigProxy nginxServiceConfigProxy1:nginxServiceConfigProxies){
                            if (i++==0){
                            }else {
                                MainTask mainTask1=new MainTask();
                                mainTask1.setId(WebUtils.id());
                                mainTask1.setDeployServiceModuleId(lastMainTask.getDeployServiceModuleId());
                                mainTask1.setDeployGoalId(lastMainTask.getDeployGoalId());
                                mainTask1.setLastId(lastMainTask.getId());
                                mainTask1.setStatus("make");

                                BasicBehavior basicBehavior1=new BasicBehavior();
                                basicBehavior1.setId(WebUtils.id());
                                basicBehavior1.setMainTaskId(mainTask1.getId());
                                basicBehavior1.setDeployServiceModuleId(mainTask1.getDeployServiceModuleId());
                                basicBehavior1.setDeployGoalId(mainTask1.getDeployGoalId());
                                basicBehavior1.setResult("");
                                basicBehavior1.setStatus("make");

                                String nginxServerId1=nginxServiceConfigProxy1.getServerId();
                                ////
                                mainTask1.setName("online");
                                basicBehavior1.setType("online:grep");

                                basicBehavior1.setClientId(nginxServerId1);

                                String domain1=nginxServiceConfigProxy1.getFrontDomain();
                                String nginxVhostConfigFile1="/lhwl/app/nginx/conf/vhost/"+domain1+".conf";
                                String command1="grep -n "+targetNodeServerIp+":"+httpPort+" "+nginxVhostConfigFile1;

                                basicBehavior.setCommand(command1);
                                ////
                                basicBehaviorService.addBasicBehavior(basicBehavior1);
                                mainTaskService.addMainTask(mainTask1);
                            }
                        }
                    }else {
                    }
                    //System.out.println("nginxServerId: "+nginxServerId+";tomcatServerId: "+tomcatServerId);
                    if(nginxServerId.equals(tomcatServerId)){
                        yesOrNo="yes";
                    }else {
                        yesOrNo="no";
                    }
                    basicBehaviorService.addBasicBehavior(basicBehavior);
                    mainTaskService.addMainTask(mainTask);
                }
            }
        }
        return  yesOrNo;
    }//识别上个环节是offline,制定下个环节是update,具体行动为update:pull

    public String offline(BasicBehavior lastBasicBehavior){//(理论上,应该在这里对 "主任务" 拆分)
        String yesOrNo="";
        BasicBehavior nextBasicBehavior=new BasicBehavior();
        nextBasicBehavior.setId(WebUtils.id());
        nextBasicBehavior.setMainTaskId(lastBasicBehavior.getMainTaskId());
        nextBasicBehavior.setDeployServiceModuleId(lastBasicBehavior.getDeployServiceModuleId());
        nextBasicBehavior.setDeployGoalId(lastBasicBehavior.getDeployGoalId());
        nextBasicBehavior.setClientId(lastBasicBehavior.getClientId());

        if (lastBasicBehavior.getType().equals("offline:grep")){
            nextBasicBehavior.setType("offline:sed");//说明上一条执行成功了,获取它的结果,为下一条操作做准备
            String result=lastBasicBehavior.getResult().replace("\n","").replaceAll("\r","");
            String line=result.substring(0,result.indexOf(":"));
            String contextOld=result.substring(result.indexOf(":")+1,result.length());
            String contextNew=contextOld.replace(" down","").replace(";"," down;");
            String commandLast=lastBasicBehavior.getCommand();
            String file=commandLast.substring(commandLast.lastIndexOf(" ")+1,commandLast.length());
            String command="sed -i  '"+line+ "c \\" +contextNew+ "' " +file;
            nextBasicBehavior.setCommand(command);
            nextBasicBehavior.setStatus("make");

            basicBehaviorService.addBasicBehavior(nextBasicBehavior);
            yesOrNo="yes";
        }
        if (lastBasicBehavior.getType().equals("offline:sed")){
            nextBasicBehavior.setType("offline:reload");
            //说明上一条执行成功了,获取它的状态,成功则继续;不用看,它一定是成功的,否则进不到这里来
            String command="/etc/init.d/nginx reload";
            nextBasicBehavior.setCommand(command);
            nextBasicBehavior.setStatus("make");

            basicBehaviorService.addBasicBehavior(nextBasicBehavior);
            yesOrNo="yes";
        }
        if (lastBasicBehavior.getType().equals("offline:reload")){
            yesOrNo="no";
        }
        return yesOrNo;
    }//在这里面识别上次行动为grep,制定下次行动为sed,告知client yes;识别上次行动为sed,制定下次行动为reload,告知client yes;识别上次行动为reload,退出offline
    public String update(BasicBehavior lastBasicBehavior){// 说明pull任务完成了(理论上,应该在这里对 "主任务" 拆分)
        String yesOrNo="";
        BasicBehavior nextBasicBehavior=new BasicBehavior();
        nextBasicBehavior.setId(WebUtils.id());
        nextBasicBehavior.setMainTaskId(lastBasicBehavior.getMainTaskId());
        nextBasicBehavior.setDeployServiceModuleId(lastBasicBehavior.getDeployServiceModuleId());
        nextBasicBehavior.setDeployGoalId(lastBasicBehavior.getDeployGoalId());
        nextBasicBehavior.setClientId(lastBasicBehavior.getClientId());

        if (lastBasicBehavior.getType().equals("update:pull")){
            nextBasicBehavior.setType("update:checkHeartbeat");//说明上一条执行成功了,获取它的结果,为下一条操作做准备
            nextBasicBehavior.setStatus("make");
            yesOrNo="yes";

            MainTask mainTask=mainTaskService.queryMainTaskById(nextBasicBehavior.getMainTaskId());
            String deployServiceModuleId=mainTask.getDeployServiceModuleId();
            DeployServiceModule deployServiceModule=deployServiceModuleService.queryDeployServiceModuleById(deployServiceModuleId);
            TomcatAndHeartbeatServiceConfig tomcatAndHeartbeatServiceConfig=tomcatAndHeartbeatServiceConfigService.queryTomcatAndHeartbeatServiceConfigById(deployServiceModule.getTargetNodeId());
            String tomcatHome=WebUtils.addSeparatorChar(tomcatAndHeartbeatServiceConfig.getTomcatHome());
            String targetWarPath=tomcatHome+"webapps/"+deployServiceModule.getFileUrl();
            String tomcatWorkDir=tomcatHome+"webapps/ROOT";
            String httpPort=tomcatAndHeartbeatServiceConfig.getHttpPort();
            String heartbeatUrl=tomcatAndHeartbeatServiceConfig.getHeartbeat();
            nextBasicBehavior.setCommand(tomcatHome+"bin/catalina.sh stop;sleep 10;"+
                    "mv "+tomcatWorkDir+"{,_"+nextBasicBehavior.getId()+"};"+
                    "mkdir -p "+tomcatHome+"webapps/ROOT;"+
                    "unzip -q "+targetWarPath+" -d "+tomcatWorkDir+"/;"+
                    "rm -f "+targetWarPath+";"+
                    tomcatHome+"bin/catalina.sh start;sleep 15;" +
                    "curl http://127.0.0.1:"+httpPort+"/"+heartbeatUrl);

            basicBehaviorService.addBasicBehavior(nextBasicBehavior);
        }
        if (lastBasicBehavior.getType().equals("update:checkHeartbeat")){
            if (lastBasicBehavior.getResult().equals("success")) {//这个成功是api给的,是程序心跳api给的
                //System.out.println(lastBasicBehavior.getResult());
                yesOrNo="no";//本环节完事了
            }else {
                yesOrNo="error";
            }
        }
        return yesOrNo;
    }//识别上次行动为
    public String online(BasicBehavior lastBasicBehavior){//你现在执行的主任务叫online,要看它是否还有子任务
        String yesOrNo="";
        //String result=lastBasicBehavior.getResult().trim();
        //System.out.println(result);
        BasicBehavior basicBehavior=new BasicBehavior();
        basicBehavior.setId(WebUtils.id());
        basicBehavior.setMainTaskId(lastBasicBehavior.getMainTaskId());
        basicBehavior.setDeployServiceModuleId(lastBasicBehavior.getDeployServiceModuleId());
        basicBehavior.setDeployGoalId(lastBasicBehavior.getDeployGoalId());
        basicBehavior.setClientId(lastBasicBehavior.getClientId());

        if (lastBasicBehavior.getType().equals("online:grep")){//这个主任务的上一个子任务是grep,那么下一个子任务就是sed
            basicBehavior.setType("online:sed");//说明上一条执行成功了,获取它的结果,为下一条操作做准备
            String result=lastBasicBehavior.getResult().replace("\n","").replaceAll("\r","");
            String line=result.substring(0,result.indexOf(":"));
            String contextOld=result.substring(result.indexOf(":")+1,result.length());
            String contextNew=contextOld.replace(" down","");
            String commandLast=lastBasicBehavior.getCommand();
            String file=commandLast.substring(commandLast.lastIndexOf(" ")+1,commandLast.length());
            String command="sed -i  '"+line+ "c \\" +contextNew+ "' " +file;
            basicBehavior.setCommand(command);
            basicBehavior.setStatus("make");
            basicBehaviorService.addBasicBehavior(basicBehavior);
            yesOrNo="yes";
        }//下一步是online:sed
        if (lastBasicBehavior.getType().equals("online:sed")){
            basicBehavior.setType("online:reload");
            //说明上一条执行成功了,获取它的状态,成功则继续;不用看,它一定是成功的,否则进不到这里来
            String command="/etc/init.d/nginx reload";
            basicBehavior.setCommand(command);
            basicBehavior.setStatus("make");

            basicBehaviorService.addBasicBehavior(basicBehavior);
            yesOrNo="yes";
        }//
        if (lastBasicBehavior.getType().equals("online:reload")){
            yesOrNo="no";
        }
        return yesOrNo;
    }

    ////////////////////////////////////////////////////////////////
    public  void basicBehaviorError(BasicBehavior basicBehavior){
        basicBehavior.setStatus("error");basicBehavior.setResult("error");basicBehaviorService.updateBasicBehavior(basicBehavior);
        String mainTaskId=basicBehavior.getMainTaskId();
        MainTask mainTask=mainTaskService.queryMainTaskById(mainTaskId);
        mainTask.setStatus("error");mainTaskService.updateMainTask(mainTask);
        String deployServiceModuleId=mainTask.getDeployServiceModuleId();
        DeployServiceModule deployServiceModule=deployServiceModuleService.queryDeployServiceModuleById(deployServiceModuleId);
        deployServiceModule.setStatus("error");deployServiceModuleService.updateDeployServiceModule(deployServiceModule);
        String deployGoalId=deployServiceModule.getDeployGoalId();
        DeployGoal deployGoal=deployGoalService.queryDeployGoalById(deployGoalId);
        deployGoal.setStatus("error");deployGoalService.updateDeployGoal(deployGoal);
    }
    public  String oneDeployServiceModuleOver(MainTask mainTask,DeployServiceModule deployServiceModule,DeployGoal deployGoal){
        mainTask.setStatus("ok");mainTaskService.updateMainTask(mainTask);
        deployServiceModule.setStatus("ok");deployServiceModuleService.updateDeployServiceModule(deployServiceModule);
        DeployServiceModule nextDeployServiceModule = deployServiceModuleService.queryDeployServiceModuleByLastId(deployServiceModule.getId());
        String yesOrNo="";
        if (nextDeployServiceModule == null) {//下一个模块不存在了,告诉client 没有了
            deployGoal.setStatus("ok");deployGoalService.updateDeployGoal(deployGoal);
            yesOrNo="no";
        } else {//总任务下还有模块需要发布
            String nextProjectModuleTypeName=deployServiceModuleService.queryProjectModuleTpyeNameByDeployServiceModuleId(deployServiceModule.getId());
            if (nextProjectModuleTypeName.equals("tomcatAndHeartbeat")) {//如果类型为心跳类型,那么就生成一个主任务和子任务
                String nextTargetNodeId = nextDeployServiceModule.getTargetNodeId();
                NginxServiceConfigProxy nextNginxServiceConfigProxy = nginxServiceConfigProxyService.queryNginxServiceConfigProxyByTargetNodeId(nextTargetNodeId);
                if(nextNginxServiceConfigProxy==null){
                    MainTask newMainTask = new MainTask(WebUtils.id(), nextDeployServiceModule.getId(), deployGoal.getId(), "update", "make", "0");
                    mainTaskService.addMainTask(newMainTask);

                    TomcatAndHeartbeatServiceConfig newTomcatAndHeartbeatServiceConfig=tomcatAndHeartbeatServiceConfigService.queryTomcatAndHeartbeatServiceConfigById(nextDeployServiceModule.getTargetNodeId());
                    ProjectModule newProjectModule=projectModuleService.queryProjectModuleById(nextDeployServiceModule.getProjectModuleId());
                    String newDeployPullRootUrl=newProjectModule.getDeployPullRootUrl();
                    String newSourceWarUrl=WebUtils.addSeparatorChar(newDeployPullRootUrl)+nextDeployServiceModule.getFileUrl();
                    String newTomcatHome=WebUtils.addSeparatorChar(newTomcatAndHeartbeatServiceConfig.getTomcatHome());
                    String newTargetWarPath=newTomcatHome+"webapps/"+nextDeployServiceModule.getFileUrl();
                    String command="wget "+newSourceWarUrl+" -O "+newTargetWarPath+";";
                    String newTomcatServerId=newTomcatAndHeartbeatServiceConfig.getServerId();
                    BasicBehavior newBasicBehavior=new BasicBehavior(WebUtils.id(),newMainTask.getId(),nextDeployServiceModule.getId(),deployGoal.getId(),command,newTomcatServerId,"","make","update:pull");
                    basicBehaviorService.addBasicBehavior(newBasicBehavior);//定义这个主任务的第一个子任务

                    TomcatAndHeartbeatServiceConfig lastTomcatAndHeartbeatServiceConfig=tomcatAndHeartbeatServiceConfigService.queryTomcatAndHeartbeatServiceConfigById(deployServiceModule.getTargetNodeId());
                    String lastTomcatServerId=lastTomcatAndHeartbeatServiceConfig.getServerId();
                    if (lastTomcatServerId.equals(newTomcatServerId)){
                        yesOrNo="yes";
                    }else {
                        yesOrNo="no";
                    }
                }else {
                    MainTask newMainTask = new MainTask(WebUtils.id(), nextDeployServiceModule.getId(), deployGoal.getId(), "offline", "make", "0");
                    mainTaskService.addMainTask(newMainTask);

                    String nextNginxServerId = nextNginxServiceConfigProxy.getServerId();
                    Server nextNginxServer = serverService.queryServerById(nextNginxServerId);
                    TomcatAndHeartbeatServiceConfig nextTomcatAndHeartbeatServiceConfig = tomcatAndHeartbeatServiceConfigService.queryTomcatAndHeartbeatServiceConfigById(nextTargetNodeId);
                    String nextTomcatServerId = nextTomcatAndHeartbeatServiceConfig.getServerId();
                    Server nextTomcatServer=serverService.queryServerById(nextTomcatServerId);
                    String ip = nextTomcatServer.getIp();
                    String httpPort = nextTomcatAndHeartbeatServiceConfig.getHttpPort();
                    String domain = nextNginxServiceConfigProxy.getFrontDomain();
                    String command = "grep -n " + ip + ":" + httpPort + " " + domain + ".conf";
                    String clientId = nextNginxServer.getId();
                    BasicBehavior newBasicBehavior = new BasicBehavior(WebUtils.id(), newMainTask.getId(), nextDeployServiceModule.getId(), deployGoal.getId(), command, clientId, "", "make", "offline:grep");
                    basicBehaviorService.addBasicBehavior(newBasicBehavior);
                    TomcatAndHeartbeatServiceConfig tomcatAndHeartbeatServiceConfig=tomcatAndHeartbeatServiceConfigService.queryTomcatAndHeartbeatServiceConfigById(deployServiceModule.getTargetNodeId());
                    String tomcatServerId=tomcatAndHeartbeatServiceConfig.getServerId();
                    if (tomcatServerId.equals(nextNginxServerId)) {
                        yesOrNo="yes";
                    } else {
                        yesOrNo="no";
                    }
                }
            }
        }
        return yesOrNo;
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(Thread.currentThread().getStackTrace()[1].getFileName()+":"
                +Thread.currentThread().getStackTrace()[1].getLineNumber()+":"
                +"已经进入doget方法,"+request.getParameter("action")+" 是action名");
        doPost(request,response);//把dopost方法优化到baseServlet抽象类中去了,使得可以按照request action执行特定的方法
        //由于action判断行为在dopost中,所以在doget中执行一下dopost就可以执行判断了,从而执行特定的方法了.
    }
}
